import LottieView from "@/components/LottieView";
import styles from "@/styles/login.module.scss";
import { Button, Form, Input, message } from "antd";
import CookieCutter from "cookie-cutter";
import { useRouter } from "next/router";
import { Component, useState } from "react";
import Welcome2LottieJson from "@/public/lottie/welcome-2.lottie.json";
import { useDeviceMode } from "@/hooks/useDeviceMode";

const LoginPage = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const mobile = useDeviceMode();

  const onFormFinished = async (form: object) => {
    setLoading(true);
    const json = await fetch("/api/login", {
      method: "POST",
      body: JSON.stringify(form),
    });
    const data = await json.json();
    if (data.code !== 200) {
      messageApi.error(data.message);
    } else {
      setCookie(data.token);
      router.push("/");
      messageApi.success(data.message);
    }
    setLoading(false);
  };

  function setCookie(token: string) {
    CookieCutter.set("Authorization", token, {
      expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
    });
  }

  return (
    <div className={styles.container}>
      {contextHolder}
      <div className={styles.aside}>
        <LottieView
          animationData={Welcome2LottieJson}
          loop={true}
          width={mobile ? "80vw" : "400px"}
          height={mobile ? "80vw" : "400px"}
        ></LottieView>
      </div>
      <div className="flex items-center justify-center">
        <Form className="w-80" onFinish={onFormFinished}>
          <h2 className="text-2xl mb-8 ">{mobile ? "🎉" : "🎉"}欢迎回来</h2>
          <Form.Item
            label=""
            name={"account"}
            required
            rules={[{ required: true, message: "请输入账号" }]}
          >
            <Input placeholder="账号"></Input>
          </Form.Item>
          <Form.Item
            label=""
            name={"password"}
            required
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input type="password" placeholder="密码"></Input>
          </Form.Item>

          <Form.Item>
            <div className="w-full  box-border mt-4">
              <Button loading={loading} htmlType="submit" block type="primary">
                进入
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

LoginPage.customLayout = (page: Component) => page;

export default LoginPage;
